import { _decorator, Component, Node, game, AudioSource, Label, ProgressBar, Sprite, Color } from 'cc';
import { mb_base_cp, mb_audio_const } from 'db://magic-book/src';
const { ccclass, property } = _decorator;

@ccclass('audio_playing_template')
export class audio_playing_template extends mb_base_cp {

    source: AudioSource = null;

    @property(Label)
    label_id: Label = null;

    @property(Label)
    label_name: Label = null;

    @property(ProgressBar)
    progressBar: ProgressBar = null;

    @property(Label)
    label_btn: Label = null;

    onLoad() {
        game.on(mb_audio_const.event_destroy_audio, this.on_destroy_audio, this);
    }

    init(source: AudioSource, is_music: boolean) {
        this.source = source;
        this.label_id.string = `${this.source.uuid}`;
        this.label_name.string = ` ${this.source.name}`;
        if (is_music) {
            this.node.getComponent(Sprite).color = Color.BLUE;
        } else {
            this.node.getComponent(Sprite).color = Color.CYAN;
        }
    }

    on_destroy_audio(source: AudioSource) {
        if (source == this.source) {
            this.node.destroy();
        }
    }

    update() {
        this.progressBar.progress = (this.source.currentTime / this.source.duration);
        this.label_btn.string = this.source.playing ? "pause" : "play";
    }

    on_click_btn() {
        if (this.label_btn.string == "pause") {
            this.source.pause();
        } else {
            this.source.play();
        }
    }

}

